# coding: utf-8
class UsersController < ApplicationController
  include UsersHelper
  before_action :set_user, only: [:show, :edit, :update, :destroy]
  #before_action :logged_in_user, only: [:index, :edit, :update, :destroy] # 只有登录才能删除用户
  before_action :correct_user, only: [:edit, :update]
  before_action :admin_user, only: :destroy #　只有管理员才能访问 destory 动作
  
  skip_before_action :authorize, only: [:create, :new]

  #skip_before_action :authorize, only: [:create]

  def index
    @users = User.order('created_at').page(params[:page])
  end

  # GET /users/1
  # GET /users/1.json
  def show
  end

  # GET /users/new
  def new
    @user = User.new
  end

  # GET /users/1/edit
  def edit
  end

  # POST /users
  # POST /users.json
  def create
    @user = User.new(user_params)

    respond_to do |format|
      if @user.save
        # 创建成功
        log_in @user
        flash[:success] = "你好！"
        format.html { redirect_to @user }
      else
        format.html { render :new }
      end
    end
  end

  # PATCH/PUT /users/1
  # PATCH/PUT /users/1.json
  def update
    respond_to do |format|
      # if @user.update(user_params)
      if @user.update_attributes(user_params)
        flash[:success] = "个人信息修改完毕"
        format.html { redirect_to @user}
        format.json { render :show, status: :ok, location: @user }
      else
        format.html { render :edit }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /users/1
  # DELETE /users/1.json
  def destroy
    User.find(params[:id]).destroy
    flash[:success] = "用户已删除"
    #redirect_to users_url
    redirect_to admin_users_path
    # @user.destroy
    # respond_to do |format|
    #   format.html { redirect_to users_url }
    #   format.json { head :no_content }
    # end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_user
      @user = User.find(params[:id])
    end

    # 白名单
    def user_params
      params.require(:user).permit(:name, :email, :password, :password_confirmation, {avatars: []})
    end

  # 确保用户已登录
  def logged_in_user
    unless logged_in?
      store_location
      flash[:danger] = "请登录!"
      redirect_to login_path
    end
  end

  # 确保是正确的用户
  def correct_user
    @user = User.find(params[:id])
    redirect_to root_path unless current_user?(@user)
  end

  private
  def admin_user
    unless admin_user?
      flash[:danger] = "没有访问的权限"
      redirect_to root_path
    end
  end
end
